package com.controller;

import com.model.UserRegisterModel;
import com.model.operation.UserOperate;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by LPFma on 2016/12/3 0003.
 */
@WebServlet(name = "UserSignUp", urlPatterns = "/UserSignUp")
public class UserSignUp extends HttpServlet {
    private final String invalid = "invalid";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*init response*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.addHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

        /*post arguments*/
        String username = request.getParameter("username");
        String passwd = request.getParameter("passwd");

        String isNameValid;
        String isPasswdValid = invalid;
        String status = "fail";

        do {
            isNameValid = UserRegisterModel.isUsernameValid(username);
            if (isNameValid.equals(invalid)) break;

            isPasswdValid = UserRegisterModel.isPasswdValid(passwd);
            if (isPasswdValid.equals(invalid)) break;

            UserOperate userOperate = new UserOperate();
            status = userOperate.IsUsernameValid(username, passwd);
        } while (false);

        String finalIsNameValid = isNameValid;
        String finalIsPasswdValid = isPasswdValid;
        String finalStatus = status;

        /* pack json map */
        Map map = new HashMap<String, String>() {
            {
                put("username", finalIsNameValid);
                put("passwd", finalIsPasswdValid);
                put("status", finalStatus);
            }
        };

        /* send json */
        JSONObject jsonObject = JSONObject.fromObject(map);
        response.getWriter().write(jsonObject.toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
